<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-08-02
 * @Time: 15:53
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Live.php
 */
namespace app\admin\controller;

use app\admin\lib\AdminController;
use app\admin\model\live\LiveChannel;
use app\admin\model\ApiResponse;
use app\api\model\live\Live;
use app\common\controller\Files;
use app\common\model\LiveStockRecommend;
use app\common\model\LiveStockSuggest;
use app\common\utils\OssUtil;
use library\v163Class;
use think\Db;
use think\db\Query;
use think\Log;
use think\Request;

class Lives extends AdminController
{
    /**
     * 频道列表
     * @return ApiResponse
     */
    public function channel_list() {
        $form = $this->getAndCheckForm([
            ['teacher_id', 'integer',],
        ]);
        $teacherId = $form['teacher_id']??-1;

        $list = LiveChannel::all(function (Query $query) use ($teacherId) {
            $query->alias('c');
            $query->join('teacher t','t.id=c.teacher_id','LEFT');
            if ($teacherId != -1) $query->where('c.teacher_id', $teacherId);
            $query->field('c.*, t.realname teacher_name');
            $query->limit($this->offset,$this->limit);
        });

        return ApiResponse::success($list);
    }

    /**
     * 创建和修改频道
     *
     * @return ApiResponse
     */
    public function channel_save() {
        $form = $this->getAndCheckForm([
            ['id', 'integer',],
            ['name', 'require',],
            ['teacher_id', 'integer',],
            ['official', 'integer',],
        ]);
        $id = intval($form['id'] ?? 0);
        $teacherId = intval($form['teacher_id'] ?? 0);

        $isNew = false;
        if ($id > 0) $model = LiveChannel::get($id);
        if (empty($model)) {
            $model = new LiveChannel();
            $isNew = true;
        }
        $model->name = $form['name'];
        $model->teacher_id = $teacherId>0 ? $teacherId : 0;
        $model->announcement = $form['announcement'] ?? null;
        $model->summary = $form['summary'] ?? null;
        $model->online_num = $form['online_num'] ?? 0;
        $model->official = $form['official'] ?? 2;

        try{
            if ($isNew) {
                $v163 = v163Class::getInstance();
                $re = $v163->channel_add($model->name);
                $v163->channel_setRecord($re['cid']);

                $model->cid = $re['cid'];
                $model->pushurl = $re['pushUrl'];
                $model->pullurlhttp = $re['httpPullUrl'];
                $model->pullurlhls = $re['hlsPullUrl'];
                $model->pullurlrtmp = $re['rtmpPullUrl'];
            }
            if (empty($model->chat_room_id)) {
                $model->chat_room_id = sha1(microtime(true).'_'.mt_rand(1111,999999));
            }
            $model->save();
            return ApiResponse::success();
        }catch (\Exception $e){
            Log::error($e);
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,$e->getMessage());
        }
    }

    /**
     * 删除频道
     * @return ApiResponse
     */
    public function channel_del() {
        if (empty(($id = input('post.id')))) {
            ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'频道id不能为空');
        }
        $ch = LiveChannel::get($id);
        if (empty($ch)) {
            ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'频道不存在');
        }
        $re = LiveChannel::check_used($id);
        if ($re) {
            ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'频道使用过，无法删除');
        }

        $chData = v163Class::getInstance()->channel_delete($ch->cid);
        if ($chData && 200==$chData['code']) {
            $ch->delete();
            return ApiResponse::success();
        } else {
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'删除频道失败');
        }
    }

    /**
     * 直播列表
     *
     * @return ApiResponse
     */
    public function list() {
        $form = $this->getAndCheckForm([
            ['page', 'integer',],
            ['rows', 'integer',],
            ['date', 'date',],
        ]);

        $query = Db::table('live l')
            ->join('teacher t','l.teacher_id=t.id')
            ->field('l.*,t.realname as teacher_name')
            ->order('start_time asc');
        if (!empty($form['date']))
            $query->where('live_date','=',$form['date']);

        $re = $query->paginate($form['rows'] ?? 10,false,[
            'page' => $form['page']??1
        ])->toArray();

        if($re['total']>0){
            foreach ($re['data'] as &$item){
                $item['bind_curriculum_id']=$item['bind_curriculum_id']??0;
            }
        }
        return ApiResponse::success($re);
    }

    /**
     * 直播创建或修改
     *
     * @return ApiResponse
     */
    public function save() {
        $form = $this->getAndCheckForm([
            ['title', 'require',],
            ['cover', 'require',],
            ['teacher_id', 'require|integer',],
            ['live_date', 'require|date',],
            ['introduce', 'require',],
            ['start_time', 'require',],
            ['end_time', 'require',],
            ['live_channel_id', 'require|integer',],
            ['bind_curriculum_id', 'integer',],
            ['password', 'length:0,4',],
        ]);

        $channel = LiveChannel::get($form['live_channel_id']);
        if (empty($channel)) return ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'无效的直播间id');

        $liveId = isset($form['id'])?$form['id']:0;
        $start_time = $form['start_time'];
        $end_time = $form['end_time'];
        if (Live::checkTimeRange($channel->id, $start_time, $end_time, $liveId)) return ApiResponse::error(ApiResponse::ERR_FORM_INVALID,'当前频道时间有重叠');
        // 自动下载内容中的远程图片并同步到oss
        if (isset($form['introduce'])) $form['introduce'] = Files::imgSync($form['introduce']);
        $data = [
            'title' => $form['title'],
            'cover' => $form['cover'],
            'teacher_id' => $form['teacher_id'],
            'live_date' => $form['live_date'],
            'introduce' => $form['introduce'],
            'start_time' => $start_time,
            'end_time' => $end_time,
            'live_price' => floatval($form['live_price'] ?? 0),
            'playback_price' => floatval($form['playback_price'] ?? 0),
            'live_channel_id' => $channel->id,
            'replay_num' => $form['replay_num']??0,
        ];
        if (isset($form['bind_curriculum_id'])) {
            $data['bind_curriculum_id'] = $form['bind_curriculum_id'] > 0 ? intval($form['bind_curriculum_id']) : null;
        }
        if(isset($form['is_encrypt']) && $form['is_encrypt']=='true'){
            $data['is_encrypt'] = true;
            $data['password']=$form['password'];
        }else{
            $data['is_encrypt'] = false;
        }
        Db::transaction(function () use ($form, $data) {
            if (isset($form['id'])) {
                $data['id'] = $form['id'];
                $model = Live::update($data);
            } else {
                $data['status'] = 0;
                $model = Live::create($data);
            }
        });

        return ApiResponse::success();
    }

    /**
     * 直播录制保存
     *
     * @return ApiResponse
     */
    public function save_video() {

        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['video_url', 'require',],
            ['duration', 'float',],
        ]);

        $live = Live::get($form['id']);
        if ($form['video_url'] != $live->video_url) {
            OssUtil::delete($live->video_url);
        }

        Live::update([
            'id' => $form['id'],
            'video_url' => $form['video_url'],
            'duration' => $form['duration'],
            'status' => 3,
        ]);

        return ApiResponse::success();
    }

    /**
     * 直播删除
     *
     * @return ApiResponse
     */
    public function del() {

        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
        ]);
        $id = $form['id'];

        $live = Live::get($id);
        if (Live::checkBeenBought($id)) {
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'已被购买');
        }
        OssUtil::delete($live->video_url);
        $live->delete();

        return ApiResponse::success();
    }

    /**
     * 操作建议列表
     * @return mixed
     */
    public function stock_suggest_list() {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
            ['cid', 'integer',],
            ['tid', 'integer',],
        ]);

        $result = LiveStockSuggest::manageList(intval($form['rows']??10),
            intval($form['page']??1), intval($form['cid']??0),
            intval($form['tid']??0));

        $result['code'] = 200;
        return $result;
    }

    /**
     * 操作建议保存
     * @return ApiResponse
     */
    public function stock_suggest_save() {

        $form = $this->getAndCheckForm([
            ['live_channel_id', 'require|integer',],
            ['teacher_id', 'require|integer',],
            ['content', 'require',],
        ]);

        if (isset($form['id'])) {
            LiveStockSuggest::update($form, [], LiveStockSuggest::getSaveFields());
        } else {
            LiveStockSuggest::create($form, LiveStockSuggest::getSaveFields());
        }

        return ApiResponse::success();
    }

    /**
     * 删除操作建议
     * @return ApiResponse
     */
    public function stock_suggest_del() {
        $form = $this->getAndCheckForm([['id','require|integer',],]);
        LiveStockSuggest::destroy($form['id']);
        return ApiResponse::success();
    }

    /**
     * 晒单接口
     *
     * @param Request $request
     * @return ApiResponse|array|\think\response\Json
     */
    public function stock_recommend(Request $request) {
        switch ($request->method()) {
            case 'GET':
                return $this->stock_recommend_list();
                break;
            case 'POST':
                return $this->stock_recommend_save();
                break;
            case 'DELETE':
                return $this->stock_recommend_del();
                break;
            default:
                return json([],405);
        }
    }

    /**
     * 晒单列表
     * @return array
     */
    private function stock_recommend_list() {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
            ['cid', 'integer',],
        ],true);

        $re = LiveStockRecommend::manageList($form['cid']??0,$form['rows']??10,$form['page']??1);
        $re['code'] = 200;
        return $re;
    }

    /**
     * 保存
     * @return ApiResponse
     */
    private function stock_recommend_save() {
        $form = $this->getAndCheckForm([
            ['live_channel_id', 'require|integer',],
            ['stock_code', 'require', '股票代码不能为空'],
            ['stock_name', 'require', '股票名称不能为空',],
            ['stock_raise', 'require', '股票涨幅不能为空',],
            ['stock_remark', 'require', '布局理由不能为空'],
        ]);
        LiveStockRecommend::upsert($form);
        return ApiResponse::success();
    }

    /**
     * 删除
     * @return ApiResponse
     */
    private function stock_recommend_del() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
        ]);
        LiveStockRecommend::destroy($form['id']);
        return ApiResponse::success();
    }

    public function getPassword(){
        $form = $this->getAndCheckForm([
            ['id', 'integer',],
        ]);
        if(isset($form['id']) && $form['id']>0){
            $live=Live::getOne($form['id'],'bind_curriculum_id');
            if($live['bind_curriculum_id']) return ApiResponse::success('');
        }
        $pass=mt_rand(1000,9999);
        return ApiResponse::success($pass);
    }

    public function save_video_url(){
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['video_url', 'require',],
        ]);
        Live::update([
            'id' => $form['id'],
            'video_url' => $form['video_url'],
            'status' => 3,
        ]);
        return ApiResponse::success();
    }

}
